package com.hongyi.utils.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: hongyi
 * @CreateTime: 2024-10-21
 */


public class StreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // 计算平方
        // 普通写法
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < numbers.size(); i++) {
            if (numbers.get(i) * numbers.get(i) > 5) { // 筛选出大于5的
                list.add(numbers.get(i) * numbers.get(i));
            }
        }


        for (Integer it : list) {
            System.out.print(it + ",");
        }
        System.out.println();
        System.out.println("-------------------------------------------------------------");


        ArrayList<Integer> list1 = new ArrayList<>();
        for (int i = 0; i < numbers.size(); i++) {
            boolean flag = false;
            if (numbers.get(i) * numbers.get(i) < 5) { // 筛选出大于5的
                flag = true;
            }
            if (!flag) {
                list1.add(numbers.get(i) * numbers.get(i));
            }
        }

        for (Integer it : list1) {
            System.out.print(it + ",");
        }
        System.out.println();
        System.out.println("-------------------------------------------------------------");


        List<Integer> squares = numbers.stream()
                .map(n -> n * n)
                .filter(n -> n > 5) // 筛选出大于5的 这里相当于if在这里增加了判断条件
                .toList();

        System.out.println("Squares greater than 5: " + squares);
    }
}
